// pages/shopcar/shopcar.js
let app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartData: [], //购物车列表
    cindex: 0, //自定义index
    selectAllStatus: false, //全选状态 默认不全选
    totalPrice: 0, //总价 开始为0
    num: 0, // 有其一未选 全选状态为false 全选则全选状态为truee
    edit: false, //编辑状态 为true显示完成 false为编辑
    orderData: null //选中商品的数据
  },
  // 点击选择商品/取消选择
  checkChange(e) {
    // 商品下标
    let index = e.currentTarget.dataset.index
    let cartData = this.data.cartData
    // 选择状态取反
    let checked = cartData[index].checked
    console.log(checked);
    cartData[index].checked = !checked


    let num = this.data.num
    //  存储选项为true的
    let sidList = []
    for (let i = 0; i < cartData.length; i++) {
      if (cartData[i].checked) {
        sidList.push(cartData[i].sid)
      }
    }
    console.log(sidList);
    // 存储到本地中，但最好用indexOf  不要总是去遍历。
    wx.setStorage({
      key: 'select',
      data: sidList
    })
    console.log(sidList);
    app.globalData.sids = sidList
    let sids = app.globalData.sids
    // 每次点击，计算ture 数量或者false 的数量
    if (cartData[index].checked) {
      num++
    } else(
      num--
    )
    // 假如true 的个数等于商品总数，那么判断状态。
    if (num == cartData.length) {
      this.setData({
        selectAllStatus: true
      })
    } else {
      this.setData({
        selectAllStatus: false
      })
    }
    console.log(num);
    this.setData({
      cartData: cartData,
      num: num,
    })
    this.getTotalPrice();
  },

  //  NavBar事件
  onClickLeft() {
    wx.showToast({
      title: '点击返回',
      icon: 'none'
    });
  },
  // 编辑状态
  onClickRight() {
    let edit = this.data.edit
    edit = !edit
    this.setData({
      edit: edit
    })
  },
  // 提交订单
  submitOrder() {
    let sid = wx.getStorageSync('select')
    console.log(sid);
    // 结算页面查询商品
    if (sid == null || sid <= 0) {
      wx.showToast({
        title: '你没有选中商品',
        icon: 'error'
      })
    } else {
      let sid = JSON.stringify(wx.getStorageSync('select'))
      console.log(sid);
      wx.navigateTo({
        url: '/pages/order/order?sid=' + sid,
      })
    }
  },
  // 删除选中
  delSelect(e) {
    let index = e.currentTarget.dataset.index
    let cartData = this.data.cartData
    let sids = app.globalData.sids
    let selectAllStatus = this.data.selectAllStatus
    console.log(cartData);
    console.log(cartData.length);
    console.log(sids);
    if (cartData.length <= 0) {
      wx.showToast({
        title: '购物车为空',
        icon: 'error'
      })
      return
    }
    if (sids == null) {
      wx.showToast({
        title: '你没有选中商品',
        icon: 'error'
      })
    } else {
      wx.showModal({
        title: '删除选中商品',
        content: '确定删除',
        success: (res) => {
          if (res.confirm) {
            console.log('确定删除');
            wx.request({
              url: 'http://www.kangliuyong.com:10002/deleteShopcart',
              method: 'POST',
              header: {
                "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
              },
              data: {
                appkey: app.globalData.appkey,
                tokenString: app.globalData.token,
                sids: JSON.stringify(wx.getStorageSync('select'))
              },
              success: (res) => {
                console.log(res);
                if (res.statusCode == 200) {
                  wx.showToast({
                    title: '删除成功',
                  });
                  // 把界面数据也给更换了，
                  wx.getStorageSync('select').forEach(item => {
                    this.data.cartData.forEach((items, index) => {
                      if (item == items.sid) {
                        this.data.cartData.splice(index, 1);
                      }
                    })
                  })
                  // 把本地数据也清空了。
                  wx.setStorage({
                    key: 'select',
                    data: []
                  })
                  this.setData({
                    cartData: cartData
                  })
                  this.getTotalPrice();
                }
                console.log(cartData);
                console.log(cartData.length);
                console.log(selectAllStatus);
                if (cartData.length == 0) {
                  selectAllStatus = false
                  this.setData({
                    selectAllStatus: selectAllStatus
                  })
                }
              }
            })
          } else if (res.cancel) {
            console.log('取消删除');

          }
        }
      })
    }

  },
  // 获取购物车数据
  onShow() {
    let token = wx.getStorageSync('token')
    console.log(token);
    if (token == '') {
      wx.showModal({
        title: '无法查看购物车',
        content: '请先登录再操作',
        success: (res) => {
          if (res.confirm) {
            console.log('用户登录');
            wx.navigateTo({
              url: '/pages/login/login',
            })
          } else if (res.cancel) {
            console.log('用户取消');
            wx.switchTab({
              url: '/pages/index/index',
            })
          }
        }
      })
    } else {
      wx.getStorage({
        key: 'token',
        success: (res) => {
          console.log(res);
          this.getProduct(res.data)
        }
      })
    }
  },
  // 查询购物车
  getProduct(token) {
    // 查询所有购物车数据
    wx.request({
      url: 'http://www.kangliuyong.com:10002/findAllShopcart',
      data: {
        appkey: app.globalData.appkey,
        tokenString: token
      },

      success: res => {
        // 记录登录的token值------------------------------------
        app.globalData.token = token;
        console.log(res);
        if (res.data.result.length == 0) {
          let selectAllStatus = this.data.selectAllStatus
          selectAllStatus = false
          this.setData({
            selectAllStatus: selectAllStatus
          })
        }

        // 定义一个就行了。
        let cartList = []

        if (this.data.cartData[0] && this.data.cartData.length == res.data.result.length) {
          cartList = this.data.cartData
        } else {
          cartList = res.data.result
          cartList.forEach(item => {
            // console.log(item);
            item.rule = item.rule.replace(/,/g, "/")
          })
        }
        let storage = wx.getStorageSync('select')
        // 选中的判断一下
        if (storage[0]) {
          cartList.forEach(items => {
            storage.forEach(item => {
              if (item == items.sid) {
                items.checked = true
              }
            })
          })
        }
        // 把数据放进去
        this.setData({
          cartData: cartList,
        })
        // 计算一下价格；
        this.getTotalPrice()
      }
    })

  },
  // 商品数量--
  reduceNum(e) {
    let index = e.currentTarget.dataset.index
    let cartData = this.data.cartData
    let count = cartData[index].count
    if (count > 1) {
      count = count - 1
      cartData[index].count = count
      this.setData({
        cartData: cartData
      })
      this.getTotalPrice();
    } else {
      this.data.count == 1
      wx.showToast({
        title: '不能再减啦!',
        icon: 'error'
      })
    }
    this.upCount(this.data.cartData[index].sid, count)

  },
  // 商品数量++
  addNum(e) {
    let index = e.currentTarget.dataset.index
    let cartData = this.data.cartData
    let count = ++cartData[index].count

    cartData[index].count = count
    this.setData({
      cartData: cartData
    })
    this.upCount(this.data.cartData[index].sid, count)
    this.getTotalPrice();
  },
  // 购物车数据库的数量更换
  upCount(sid, count) {
    console.log(11111);
    console.log(token);
    wx.request({
      url: 'http://www.kangliuyong.com:10002/modifyShopcartCount',
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
      },
      data: {
        appkey: app.globalData.appkey,
        tokenString: app.globalData.token,
        sid: sid,
        count: count
      }
    })
  },
  // 全选/取消全选
  selectAll() {
    console.log(app.globalData.sids);
    let selectAllStatus = this.data.selectAllStatus
    let cartData = this.data.cartData
    selectAllStatus = !selectAllStatus
    for (let i = 0; i < cartData.length; i++) {
      cartData[i].checked = selectAllStatus
    }
    // 保存选中状态的商品sid
    let sidList = []
    for (let j = 0; j < cartData.length; j++) {
      if (cartData[j].checked) {
        sidList.push(cartData[j].sid)
      }
    }
    // 保存在本地中
    wx.setStorage({
      key: 'select',
      data: sidList
    })
    //取消全选 num为0
    if (!selectAllStatus) {
      this.data.num = 0
    }
    app.globalData.sids = sidList
    this.setData({
      selectAllStatus: selectAllStatus,
      cartData: cartData,
    })
    this.getTotalPrice();
  },
  // 计算总价
  getTotalPrice() {
    let cartData = this.data.cartData;
    let total = 0
    for (let i = 0; i < cartData.length; i++) {
      if (cartData[i].checked) {
        total += cartData[i].count * cartData[i].price
      }
    }
    this.setData({
      cartData: cartData,
      totalPrice: total.toFixed(2)
    })
  },
  //回到首页
  pushHome() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  //跳转菜单页面
  pushMenu() {
    wx.switchTab({
      url: '/pages/menu/menu',
    })
  }

})